﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using LinqToTwitter;

namespace UserStreamsParser.Test
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void startButton_Click(object sender, RoutedEventArgs e)
        {
            this.startButton.IsEnabled = false;

            var twCtx = new TwitterContext(new PinAuthorizer()
            {
                UserAgent = "UserStreamsParserTest",
                CredentialStore = new InMemoryCredentialStore()
                {
                    ConsumerKey = this.consumerKeyBox.Text,
                    ConsumerSecret = this.consumerSecretBox.Text,
                    OAuthToken = this.oauthTokenBox.Text,
                    OAuthTokenSecret = this.oauthTokenSecretBox.Text
                }
            });

            var list = new ObservableCollection<string>();

            var parser = twCtx.Streaming.Where(_ => _.Type == StreamingType.User).CreateParser();

            parser.ReceivedStatus += (_sender, _e) => this.Dispatcher.BeginInvoke(new Action(() =>
                list.Insert(0, string.Format("@{0}: {1}", _e.Status.User.ScreenNameResponse, _e.Status.Text))));
            
            parser.ReceivedDirectMessage += (_sender, _e) => this.Dispatcher.BeginInvoke(new Action(() =>
                list.Insert(0, string.Format("DM From @{0} To @{1}: {2}", _e.DirectMessage.SenderScreenName, _e.DirectMessage.RecipientScreenName, _e.DirectMessage.Text))));
            
            parser.ReceivedDeletedStatus += (_sender, _e) => this.Dispatcher.BeginInvoke(new Action(() =>
                list.Insert(0, "Deleted Status: " + _e.Id)));
            
            parser.ReceivedDeletedDirectMessage += (_sender, _e) => this.Dispatcher.BeginInvoke(new Action(() =>
                list.Insert(0, "Deleted DM: " + _e.Id)));
            
            parser.ReceivedEvent += (_sender, _e) => this.Dispatcher.BeginInvoke(new Action(() =>
                list.Insert(0, string.Format("{0}Event: @{1}", _e.Event.ToString(), _e.Source.ScreenNameResponse))));
            
            parser.ReceivedFriends += (_sender, _e) => this.Dispatcher.BeginInvoke(new Action(() =>
                list.Insert(0, "Friends: " + string.Join(", ", _e.Friends))));
            
            parser.ReceivedUnknownData += (_sender, _e) => this.Dispatcher.BeginInvoke(new Action(() =>
                list.Insert(0, _e.Json)));

            this.listBox.DataContext = list;

            this.Closing += (_sender, _e) => parser.Close();
        }
    }
}
